from conanbase import ConanBase,copy
from conan.tools.files import chdir
import os
import subprocess
import platform

required_conan_version = ">=2.13.0"


class AppConan(ConanBase):

    def package_info(self):
        pass

    def gen_drivers(self):
        print(f"原始工作目录: {self.current_working_dir}")
        drivers_path = "src/lualib/mock/drivers"
        target_path = os.path.join(self.current_working_dir, drivers_path)
        print(f"目标路径: {target_path}")
        kernel_path = "src/lualib/mock/kernel"
        target_kernel_path = os.path.join(self.current_working_dir, kernel_path)
        try:
            os.chdir(target_path)
            os.mkdir(target_kernel_path)
            print(f"当前工作目录：{os.getcwd()}")
            script_path = "./build_driver.sh"
            kernel_path = self.buildenv.vars(self).get("KERNEL_PATH")
            sdk_root = self.buildenv.vars(self).get("CONAN_CMAKE_FIND_SDK_ROOT")
            print(f"sdk_root: {sdk_root}")
            print(f"kernel_path: {kernel_path}")
            if os.path.exists(script_path):
                os.chmod(script_path, 0o755)
                result = subprocess.run(["/bin/sh", script_path, f'{kernel_path}', f'{sdk_root}'], check=True, capture_output=True, text=True)
            else:
                raise FileNotFoundError(f"错误: 脚本不存在: {script_path}")
            return True
        except subprocess.CalledProcessError as e:
            print(f"脚本执行失败，退出状态码: {e.returncode}")
            print(f"标准错误: {e.stderr}")
            raise  # 重新抛出或处理
        except Exception as e:
            print(f"发生错误: {e}")
            raise
        finally:
            os.chdir(self.current_working_dir)
            print(f"已恢复工作目录: {os.getcwd()}")

    def gen_mctp_data(self):
        print(f"原始工作目录: {self.current_working_dir}")
        mctp_dir = "src/lualib/mock/data/mockdata/PCIeCard"
        
        # 更安全的路径拼接方式
        mctp_path = os.path.join(self.current_working_dir, mctp_dir)
        print(f"目标路径: {mctp_path}")
        
        try:
            # 检查目标路径是否存在
            if not os.path.exists(mctp_path):
                raise FileNotFoundError(f"错误: 路径不存在: {mctp_path}")
            
            # 切换到目标目录
            os.chdir(mctp_path)
            print(f"当前工作目录：{os.getcwd()}")
            
            script_path = "make_bin.py"
            if os.path.exists(script_path):
                # 执行脚本
                result = subprocess.run(
                    ["python3", script_path], 
                    check=True, 
                    capture_output=True, 
                    text=True
                )
                # 可以打印脚本输出以便调试
                print(f"脚本输出: {result.stdout}")
                if result.stderr:
                    print(f"脚本错误: {result.stderr}")
                    raise
            else:
                raise FileNotFoundError(f"错误: 脚本不存在: {script_path}")
                
            return True
            
        except subprocess.CalledProcessError as e:
            print(f"脚本执行失败: {e}")
            print(f"标准错误: {e.stderr}")
            raise
            
        except Exception as e:
            print(f"发生错误: {e}")
            import traceback
            traceback.print_exc()  # 打印完整的堆栈跟踪
            raise
            
        finally:
            # 确保总是恢复原始目录
            try:
                os.chdir(self.current_working_dir)
                print(f"已恢复工作目录: {os.getcwd()}")
            except Exception as e:
                print(f"恢复工作目录失败: {e}")
    
    def build(self):
        with chdir(self, self.source_folder):
            try:
                self.current_working_dir = os.getcwd()
                self.gen_drivers()
                self.gen_mctp_data()
            except FileNotFoundError as e:
                self.output.error(f"错误: {e}")
                raise
        super().build()
